﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MMessaging.MessagingEx.Common
{
	public class MMessagingHandler<TMESSAGETYPE>
	{
		private List<MMessageProcessing<TMESSAGETYPE>> _allRunningHandlers = new List<MMessageProcessing<TMESSAGETYPE>>();

		private MMessageProcessing<TMESSAGETYPE>.HandlerFunc _handler;
		private MMessagingHandlerContext<TMESSAGETYPE> _context; 

		public MMessagingHandler(MMessageProcessing<TMESSAGETYPE>.HandlerFunc handler )
		{
			_handler = handler;
			_context = new MMessagingHandlerContext<TMESSAGETYPE>();
		}

		public void Process(TMESSAGETYPE message)
		{
			_context.CurrentMessage = message;
			_allRunningHandlers.RemoveWhere(handler=>handler.IsFinished);
			foreach (var handler in _allRunningHandlers)
				handler.Tick(message);
			var newHandler = new MMessageProcessing<TMESSAGETYPE>("first level handler", _context, _handler);
			if ( newHandler.Tick(message) )
				_allRunningHandlers.Add(newHandler);
		}
	}
}
